package com.njdf.util;

import java.sql.*;

public class DBUtil {
    private static final String URL="jdbc:mysql://localhost:3306/aa";
    private static final String USERNAME="root";
    private static final String PASSWORD="12345";
    private static Connection conn;
    private static PreparedStatement pstm;
    private static ResultSet rs;
    private static int count;

    public static Connection getConn() throws ClassNotFoundException, SQLException {
        Class.forName("com.mysql.jdbc.Driver");
        conn=DriverManager.getConnection(URL,USERNAME,PASSWORD);
        return conn;
    }
    public static ResultSet select(String sql,Object[] params){
        try {
            pstm=CreatePstm(sql, params);
            rs=pstm.executeQuery();
            return rs;
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            return null;
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        } catch(Exception e){
            e.printStackTrace();
            return null;
        }
    }

    public static boolean update(String sql,Object[] params){
        try {
            pstm=CreatePstm(sql, params);
            count=pstm.executeUpdate();
            if(count>0){
                return true;
            }
            else{
                return  false;
            }
        } catch (SQLException e) {
            e.printStackTrace();
            return  false;
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            return  false;
        }catch (Exception e){
            e.printStackTrace();
            return  false;
        }finally {
            getClose();
        }
    }

    private static PreparedStatement CreatePstm(String sql, Object[] params) throws SQLException, ClassNotFoundException {
        pstm = getConn().prepareStatement(sql);
        if (params != null) {
            for (int i = 0; i < params.length; i++) {
                pstm.setObject(i + 1, params[i]);
            }
        }
        return pstm;
    }

    public static void getClose(){
            try {
                if(rs!=null) {
                    rs.close();
                }
                if(pstm!=null) {
                    pstm.close();
                }
                if(conn!=null) {
                    conn.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
    }
}

